package com.yunduo.world.handler;

import com.yunduo.world.entity.EntityInfo;
import com.yunduo.world.factory.ChannelWorker;
import com.yunduo.world.factory.WorldFactory;
import com.yunduo.world.utils.ClientUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 所有请求的接收类
 */
@Slf4j
public class WorldServerHandler extends SimpleChannelInboundHandler<EntityInfo.Entity> {

    // 首次连接
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ClientUtils.put(ctx.channel(),"临时"+ctx.channel().id().toString());
        log.info("客户端 "+ ctx.channel().id() + " 连接成功");
    }

    // 分配业务处理器
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, EntityInfo.Entity entityInfo) throws Exception {
        ChannelWorker channelWorker = WorldFactory.createChannelWorker(channelHandlerContext, entityInfo);
        channelWorker.execute();
    }

    // 异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error(cause.getMessage());
        ClientUtils.removeChannel(ctx.channel());
    }
}
